# encoding: utf-8
"""
@author: 夏洛
@QQ: 1972386194
@file: 人人车.py
"""
from fontTools.ttLib import TTFont, BytesIO
'''
奔驰-奔驰C级 2014款 C 160 经典型 Grand Edition  这个是你爬的数据
奔驰-奔驰C级 2013款 C 180 经典型 Grand Edition  网页真实数据
'''
import requests

def request(url):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36"
    }
    res = requests.get(url,headers=headers)
    return res

def get_font():
    url  = 'https://misc.rrcimg.com/ttf/rrcttf8e507398d9896e3d09053cb30d20ccf7.woff'
    font_res = request(url)
    with open('rrc.woff','wb') as f:
        f.write(font_res.content)


font_aa = TTFont('rrc.woff')
glyf = font_aa['glyf']
# # 获取请求到的字体code和name的对应关系
code_name_map = font_aa.getBestCmap()

relation_table = {"zero": "0", "one": "1", "two": "2", "four": "3", "three": "4", "five": "5", "seven": "6","nine": "7", "six": "8", "eight": "9"}

from io import BytesIO

import requests
from fontTools.ttLib import TTFont
from lxml import etree
session = requests.session()
maps = lambda x:x[0] if x else x
import re

def woff_font(font_url):
    '''获取字体真实对应关系'''
    newmap = {}
    resp = session.get(font_url)  # 请求字体链接
    woff_data = BytesIO(resp.content)  # 保存字体数据
    font = TTFont(woff_data)  # 读取woff数据
    glyf = font['glyf']  # 获取请求到的字体形状
    # 建立基础的字体和字体形状的对应关系
    base_font_map = {
        0: glyf['zero'],
        1: glyf['one'],
        2: glyf['two'],
        3: glyf['four'],
        4: glyf['three'],
        5: glyf['five'],
        6: glyf['seven'],
        7: glyf['nine'],
        8: glyf['six'],
        9: glyf['eight'],
    }
    code_name_map = font.getBestCmap()  # 获取请求到的字体code和name的对应关系
    font.close()
    for code, name in code_name_map.items():
        codestr = str(code - 48)  # 根据分析结果需要减去48
        current_shape = glyf[name]  # 根据name获取字体形状
        for number, shape in base_font_map.items():  # 遍历基础字体形状对应关系
            if shape == current_shape:  # 判断，如果两个字体形状相等
                newmap[codestr] = str(number)  # 将字体编码和字体添加到字典
    return newmap

def font_file(r):
    # 从网页里面获取字体
    font_url = re.search(r"url\('(.*\.woff)'\)", r).group(1)
    return font_url

def get_index():
    url = 'https://www.renrenche.com/bj/ershouche/p2/?&plog_id=838083390d4b077a45852d11065f60ad'
    res = session.get(url).text
    html = etree.HTML(res)
    fonts = font_file(res)
    print(fonts)
    items = html.xpath('//ul[@class="row-fluid list-row js-car-list"]/li')
    for i in items:
        title = maps(i.xpath('.//h3/text()'))
        font = woff_font('https://misc.rrcimg.com/ttf/rrcttf963b849adcb454e35139b401f7a88822.woff')
        trans_title = "".join([i if not i.isdigit() else font[i] for i in title])  # 替换错误字体，获取真实标题
        print(trans_title)

get_index()

